export const getPathByKey = (currentKey, data, keyName = 'id') => {
    let result = []
    let traverse = (currentKey, path, data) => {
        if (!data || !data.length) return

        for (let item of data) {
            path.push(item)

            if (item[keyName] === currentKey) {
                result = JSON.parse(JSON.stringify(path))
                return;
            }

            const children = Array.isArray(item.children) ? item.children : []
            traverse(currentKey, path, children)

            path.pop()

        }
    }

    traverse(currentKey, [], data)

    return result
}

/**  给树形结构添加层级 */
export const arrayTreeAddLevel = (array, levelName = 'level', childrenName = 'children') => {
    if (!Array.isArray(array)) return []
    const recursive = (array, level = 0) => {
        level++
        return array.map(item => {
            item[levelName] = level
            const child = item[childrenName]
            if (child && child.length) recursive(child, level)
            return item
        })
    }
    return recursive(array)
}

/**  根据key,获取树的对应数据 */
export const getCodesByKey = (data, key = 'level') => {
    const result: Array<number | string> = []

    const traverse = (node) => {
        if (node[key]) {
            result.push(node[key])
        }

        if (node.children?.length) {
            node.children.forEach(traverse)
        }
    }

    data.forEach(traverse)

    return result;
}

/**  获取树形结构最大层数 */
export const getTreeLevel = (treeData) => {
    let maxLevel = 0;

    // (function callBack(treeData, level) {
    //     ++level;
    //     maxLevel = Math.max(level, maxLevel);
    //     for (let i = 0; i < treeData.length; i++) {
    //         let item = treeData[i];
    //         if (item.children && item.children.length > 0) {
    //             callBack(item.children, level);
    //         } else {
    //             delete item.children;
    //         }
    //     }
    // })(treeData, 0);

    const callBack = (treeData, level = 0) => {
        ++level
        maxLevel = Math.max(level, maxLevel);
        for (let i = 0; i < treeData.length; i++) {
            let item = treeData[i];
            if (item.children && item.children.length > 0) {
                callBack(item.children, level);
            } else {
                delete item.children;
            }
        }
    }

    callBack(treeData, 0)

    return maxLevel;
};
